package com.test.wog.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.test.wog.bean.Node;
import com.test.wog.util.GeometryTrimUtil;
import com.test.wog.util.HttpRequestUtil;
import com.test.wog.util.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 *
 * @author linxun@buaa.edu.cn
 * @since 2020-01-26
 */
@Repository
public class NodeDAOImpl implements NodeDAO {

    @Autowired
    JdbcTemplate jdbc;
    @Autowired
    GeometryTrimUtil gtu;
    @Autowired
    PropertyUtil pu;
    @Autowired
    HttpRequestUtil hu;

    @Override
    public List<Node> getNodeByName(String name) {
        String sql = "select id, name, type, " + gtu.trimPoint("ST_ASTEXT(geom)") + " as geom from critical_node where name = ?";
        List<Node> nodeList = jdbc.query(
                sql,
                new Object[]{name},
                new BeanPropertyRowMapper(Node.class)
        );
        return nodeList;
    }

    @Override
    public Node getNodeByID(int id) {
        String sql = "select id, name, type, " + gtu.trimPoint("ST_ASTEXT(geom)") + " as geom from critical_node where id = ?";
        List<Node> nodeList = jdbc.query(
                sql,
                new Object[]{id},
                new BeanPropertyRowMapper(Node.class)
        );
        return nodeList.get(0);
    }

    @Override
    public List<Node> getNodeByType(String type) {
        String sql = "select id, name, type, " + gtu.trimPoint("ST_ASTEXT(geom)") + " as geom from critical_node where type = ?";
        List<Node> nodeList = jdbc.query(
                sql,
                new Object[]{type},
                new BeanPropertyRowMapper(Node.class)
        );
        return nodeList;
    }

    @Override
    public List<Node> getAllNode() {
        String sql = "select id, name, type,  " + gtu.trimPoint("ST_ASTEXT(geom)") + " as geom from critical_node";
        List<Node> nodeList = jdbc.query(
                sql,
                new Object[]{},
                new BeanPropertyRowMapper(Node.class)
        );
        return nodeList;
    }

    @Override
    public List<Node> getNodeByLoc(double lon, double lat) {//找一个离lon,lat最近的POI
        String sql = "select id, name, type, " + gtu.trimPoint("ST_ASTEXT(geom)") + " as geom from critical_node where ST_Distance_Sphere(POINT(?, ?),geom) = (select min(ST_Distance_Sphere(POINT(?, ?),geom)) from critical_node)";
        List<Node> nodeList = jdbc.query(
                sql,
                new Object[]{lon, lat, lon, lat},
                new BeanPropertyRowMapper(Node.class)
        );
        return nodeList;
    }

    @Override
    public List<Node> getNodeByLocFromAmap(double lon, double lat) {
        //output=xml&location=116.310003,39.991957&key=<用户的key>&radius=1000&extensions=all
        Map<String, String> param = new HashMap<>();
        param.put("key", pu.getProjectConfig("key"));//传入API-KEY
        param.put("location", lon + "," + lat);
        param.put("batch", "true");
        param.put("radius", "1000");
        JSONObject jo = hu.getJSONFromWebAPI(pu.getProjectConfig("regeocode-api"), param);//根据配置文件中的路径url
        List<Node> nodeList = new ArrayList<>();
        JSONArray POIArray = jo.getJSONArray("regeocodes");
        for (int i = 0; i < POIArray.size(); i++) {
            Node node = Node.builder()
                    .name(
                            POIArray.getJSONObject(i).getString("formatted_address")
                    )
                    .geom(lon + " " + lat)
                    .build();
        }
        return nodeList;
    }

    @Override
    public List<Node> getNodeByNameFromAmap(String name) {
        Map<String, String> param = new HashMap<>();
        param.put("key", pu.getProjectConfig("key"));//传入API-KEY
        param.put("address", name);
        param.put("city", "北京");
        JSONObject jo = hu.getJSONFromWebAPI(pu.getProjectConfig("geocode-api"), param);//根据配置文件中的路径url
        List<Node> nodeList = new ArrayList<>();
        JSONArray POIArray = jo.getJSONArray("geocodes");
        for (int i = 0; i < POIArray.size(); i++) {
            Node node = Node.builder()
                    .name(
                            POIArray.getJSONObject(i).getString("formatted_address")
                    )
                    .geom(POIArray.getJSONObject(i).getString("location").replace(",", " "))
                    .build();
        }
        return nodeList;
    }

    @Override
    public int insertNode() {//将json形式的点加入到数据库中
        String json = "{type:[{pos:lon,lat,name:}]}";
        int insertNum = 0;
        JSONObject jo = JSON.parseObject(json);
        Set<String> typeSet = jo.keySet();
        for(String type: typeSet){
            JSONArray ja = jo.getJSONArray(type);
            for (int i = 0; i < ja.size(); i++) {
                String geom = ja.getJSONObject(i).getString("pos");
                geom = "POINT(" + geom.replace(","," ") + ")";
                String name = ja.getJSONObject(i).getString("name");
                String sql = "INSERT into critical_node(name, type, geom) values(?,?,ST_GEOMFROMTEXT(?))";
                insertNum += jdbc.update(sql, name, type, geom);
            }
        }
        return insertNum;
    }

}
